package com.example.demo.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.example.demo.util.GenerateMybatisPlus;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description:
 * @Author:
 * @Date:
 * @Version:
 */
@RestController
public class TestController {

//    @Value("${db.diver_name}")
//    private String diverName;
//    @Value("${db.url}")
//    private String url;
//    @Value("${db.password}")
//    private String password;
//    @Value("${db.username}")
//    private String username;

    private  Map<String,String> map = new HashMap<>();

    @PostMapping("/config")
    public String config(@RequestBody JSONObject jsonObject){
        if(StrUtil.isEmpty(jsonObject.getStr("divername"))){
            return "divername字段不能为空 如：com.mysql.cj.jdbc.Driver";
        }
        if(StrUtil.isEmpty(jsonObject.getStr("url"))){
            return "url字段不能为空 如：jdbc:mysql://127.0.0.1:3306/表名?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai";
        }
        if(StrUtil.isEmpty(jsonObject.getStr("username"))){
            return "username字段不能为空 如：root";
        }
        if(StrUtil.isEmpty(jsonObject.getStr("password"))){
            return "password字段不能为空 如：123123";
        }

        try {
            //校验数据库连接是否成功
            Class.forName(jsonObject.getStr("divername"));
            DriverManager.getConnection(jsonObject.getStr("url"), jsonObject.getStr("username"), jsonObject.getStr("password"));
        }catch (Exception e){
            return "error 数据库连接失败";
        }

        //放入字段生成代码时使用
        map.put("divername",jsonObject.getStr("divername").trim());
        map.put("url",jsonObject.getStr("url").trim());
        map.put("username",jsonObject.getStr("username").trim());
        map.put("password",jsonObject.getStr("password").trim());

        return "success";
    }

    @PostMapping("/generate")
    public String generate(@RequestBody JSONObject jsonObject){

        if(CollectionUtils.isEmpty(map)){
            return "请配置数据库或调用Post  /config接口 Json格式参数：{\"diverName\":\"\",\"url\":\"\",\"password\":\"\",\"username\":\"\"} ";
        }
        //作者
        String author = jsonObject.getStr("author");
        //过滤表前缀
        String filterPrefix = jsonObject.getStr("filterPrefix");
        //表名
        String tablename = jsonObject.getStr("tablename");
        //获取到相关报名,例如:com.example.daoproject
        String packageName = jsonObject.getStr("package");
        //获取到代码保存的路径 例:D:/projectCode/svnproject/java开发框架/02_开发库/03_开发文档/code/hncxlhframe/hncxlh-project-demo/src/main/java
        String path = jsonObject.getStr("path");
        if(StrUtil.isEmpty(tablename)){
            String table = map.get("url").substring(0, map.get("url").indexOf("?"));
            table = table.substring(table.lastIndexOf("/")+1);
            String sql = "select TABLE_NAME from information_schema.tables where TABLE_SCHEMA ='"+ table +"'";
            try{
                Class.forName(map.get("divername"));
                Connection connection = DriverManager.getConnection(map.get("url"), map.get("username"), map.get("password"));
                PreparedStatement statement = connection.prepareStatement(sql);
                ResultSet resultSet = statement.executeQuery();
                while (resultSet.next()){
                    tablename += resultSet.getString("TABLE_NAME") + ",";
                }
            }catch (Exception e){
                return "tablename 为空";
            }
        }

        for (String s : tablename.split(",")) {
            if(StrUtil.isEmpty(s)){
                continue;
            }
            new GenerateMybatisPlus().generate(
                    map.get("url"),
                    map.get("username"),
                    map.get("password"),
                    map.get("divername"),
                    s,
                    packageName,
                    false,
                    path,
                    author,
                    filterPrefix);
        }

        return "success";

    }

}
